package com.zaydanwu.cla.controller.students;

import com.zaydanwu.cla.model.Students;
import com.zaydanwu.cla.model.result.ApiResult;
import com.zaydanwu.cla.service.StudentsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @BelongsProject: cla
 * @BelongsPackage: com.zaydanwu.cla.controller.students
 * @Author: zaydanwu
 * @CreateTime: 2018-12-10 22:56
 * @Description:
 */
@RestController
@RequestMapping("/cla/api")
@Slf4j
public class UserController {

    @Resource
    private StudentsService studentsService;

    @RequestMapping("/studentsLogin")
    public ApiResult<Students> studentsLogin(@RequestParam Long stuNo,@RequestParam String password) {
        if (StringUtils.isEmpty(stuNo)) {
            return ApiResult.failure("1000", "无对应的学生信息");
        }
        String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        Students studentMessage = studentsService.getStudentMessage(stuNo, md5Pwd);
        studentMessage.setPassword(null);
        return ApiResult.success(studentMessage);
    }

    @RequestMapping("/saveStudentMessage")
    public ApiResult<Object> saveStudentMessage(@Valid @RequestBody Students students, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            return ApiResult.failure("1001", "参数校验失败");
        }
        String md5Pwd = DigestUtils.md5DigestAsHex(students.getPassword().getBytes());
        students.setPassword(md5Pwd);
        int i = studentsService.saveStudentMessage(students);
        System.out.println();
        return ApiResult.success(i);
    }
}
